<template>
  <div class="min-h-screen bg-gray-50 pb-safe">
    <!-- 导航栏 -->
    <van-nav-bar
      :title="isEditMode ? '修改资料' : '填写资料'"
      left-text="返回"
      left-arrow
      @click-left="handleBack"
      fixed
      placeholder
    />

    <!-- 表单内容 -->
    <div class="p-3">
      <div
        v-if="loading"
        class="flex items-center justify-center min-h-[300px]"
      >
        <van-loading type="spinner" color="#1989fa" />
      </div>
      <van-form v-else @submit="onSubmit" ref="formRef" class="space-y-3">
        <!-- 基本信息 -->
        <van-cell-group inset title="基本信息" class="text-sm">
          <van-field
            v-model="formData.name"
            name="name"
            label="姓名"
            placeholder="请输入姓名"
            :rules="[{ required: true, message: '请填写姓名' }]"
            :label-class="'required'"
          />
          <van-field
            v-model="formData.gender"
            name="gender"
            label="性别"
            is-link
            readonly
            placeholder="请选择性别"
            @click="showGenderPicker = true"
            :rules="[{ required: true, message: '请选择性别' }]"
            :label-class="'required'"
          />
          <van-field
            v-model="formData.marital_status_desc"
            name="marital_status_desc"
            label="婚姻状况"
            :label-class="'required'"
            placeholder="请选择"
            readonly
            @click="showMaritalStatusPicker = true"
            :rules="[{ required: true, message: '请描述您的婚姻状况' }]"
          />
          <van-field
            v-model="formData.birth_year"
            name="birth_year"
            label="出生年份"
            :label-class="'required'"
            placeholder="请选择"
            readonly
            @click="showBirthYearPicker = true"
            :rules="[{ required: true, message: '请选择出生年份' }]"
          />
          <van-field
            v-model="formData.hometown"
            name="hometown"
            label="户籍地"
            :label-class="'required'"
            placeholder="请输入户籍所在地"
            :rules="[{ required: true, message: '请输入户籍所在地' }]"
          />
          <van-field
            v-model="formData.contact"
            name="contact"
            label="联系方式"
            :label-class="'required'"
            placeholder="请输入手机号码"
            :rules="[
              { required: true, message: '请输入手机号码' },
              { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码' },
            ]"
          />
          <van-field
            v-model="formData.work_location"
            name="work_location"
            label="工作地点"
            :label-class="'required'"
            placeholder="请输入工作地点"
            :rules="[{ required: true, message: '请输入工作地点' }]"
          />
          <van-field
            v-model="formData.education"
            name="education"
            label="学历"
            :label-class="'required'"
            placeholder="请选择"
            readonly
            @click="showEducationPicker = true"
            :rules="[{ required: true, message: '请选择学历' }]"
          />
        </van-cell-group>

        <!-- 个人条件 -->
        <van-cell-group inset title="个人条件" class="text-sm">
          <van-field
            v-model="formData.height"
            type="digit"
            name="height"
            label="身高(cm)"
            :label-class="'required'"
            placeholder="请输入身高"
            :rules="[
              { required: true, message: '请输入身高' },
              { validator: validateHeight, message: '身高范围在140-220之间' },
            ]"
          />
          <van-field
            v-model="formData.weight"
            type="digit"
            name="weight"
            label="体重(kg)"
            placeholder="请输入体重（选填）"
            :rules="[
              { validator: validateWeight, message: '体重范围在30-150之间' },
            ]"
          />
          <van-field
            v-model="formData.zodiac"
            name="zodiac"
            label="星座"
            placeholder="请选择（选填）"
            readonly
            @click="showZodiacPicker = true"
          />
          <van-field
            v-model="formData.occupation"
            name="occupation"
            label="职业"
            :label-class="'required'"
            placeholder="请输入您的职业"
            :rules="[{ required: true, message: '请输入职业' }]"
          />
          <van-field
            v-model="formData.income"
            name="income"
            label="月收入"
            :label-class="'required'"
            placeholder="请选择"
            readonly
            @click="showIncomePicker = true"
            :rules="[{ required: true, message: '请选择月收入范围' }]"
          />
          <van-field
            v-model="formData.family"
            name="family"
            label="家庭成员"
            type="textarea"
            rows="2"
            placeholder="请简单描述您的家庭成员构成（选填）"
          />
          <van-field
            v-model="formData.housing"
            name="housing"
            label="住房情况"
            :label-class="'required'"
            placeholder="请选择"
            readonly
            @click="showHousingPicker = true"
            :rules="[{ required: true, message: '请选择住房情况' }]"
          />
          <van-field
            v-model="formData.car"
            name="car"
            label="是否有车"
            :label-class="'required'"
            placeholder="请选择"
            readonly
            @click="showCarPicker = true"
            :rules="[{ required: true, message: '请选择是否有车' }]"
          />
          <van-field
            v-model="formData.hobbies"
            name="hobbies"
            label="兴趣爱好"
            type="textarea"
            rows="3"
            placeholder="请描述您的兴趣爱好"
          />
          <van-field
            v-model="formData.personality"
            name="personality"
            label="性格特点"
            type="textarea"
            rows="3"
            placeholder="请描述您的性格特点"
          />
        </van-cell-group>

        <!-- 照片上传 -->
        <van-cell-group inset title="照片上传" class="text-sm">
          <van-cell>
            <van-uploader
              v-model="formData.photos"
              :max-count="8"
              :after-read="handlePhotoChange"
              multiple
              :preview-size="64"
              preview-full-image
              image-fit="cover"
              upload-text="上传照片"
              :before-read="beforePhotoRead"
            >
              <template #preview-cover="{ file }">
                <div
                  v-if="file.status === 'uploading'"
                  class="absolute inset-0 flex items-center justify-center bg-black/70"
                >
                  <div class="text-center">
                    <van-loading type="spinner" size="20px" color="#fff" />
                    <div class="mt-1 text-white text-xs">上传中...</div>
                  </div>
                </div>
              </template>
            </van-uploader>
            <div class="mt-2 text-xs text-gray-500">请上传1-8张照片</div>
          </van-cell>
        </van-cell-group>

        <!-- 自我介绍 -->
        <van-cell-group inset title="自我介绍" class="text-sm">
          <van-field
            v-model="formData.introduction"
            name="introduction"
            type="textarea"
            placeholder="请简单介绍一下自己"
            :autosize="{ minHeight: 100 }"
          />
        </van-cell-group>

        <!-- 择偶要求 -->
        <van-cell-group inset title="择偶要求" class="text-sm">
          <van-field
            v-model="formData.accept_divorced"
            name="accept_divorced"
            label="接受离异"
            :label-class="'required'"
            placeholder="请选择"
            readonly
            @click="showAcceptDivorcedPicker = true"
            :rules="[{ required: true, message: '请选择是否接受离异' }]"
          />
          <van-field
            v-model="formData.requirements"
            name="requirements"
            label="择偶要求"
            :label-class="'required'"
            type="textarea"
            rows="4"
            placeholder="请描述您的择偶要求，如年龄、身高、性格等方面的期望"
            :rules="[{ required: true, message: '请填写择偶要求' }]"
          />
        </van-cell-group>

        <!-- 提交按钮 -->
        <div class="px-3 pb-3">
          <van-button
            round
            block
            type="primary"
            native-type="submit"
            :loading="submitting"
            size="normal"
          >
            {{ isEditMode ? "保存修改" : "提交" }}
          </van-button>
        </div>
      </van-form>
    </div>

    <!-- 选择器 -->
    <van-popup v-model:show="showEducationPicker" position="bottom">
      <van-picker
        :columns="educationColumns"
        @confirm="onEducationConfirm"
        @cancel="showEducationPicker = false"
        title="选择学历"
        show-toolbar
      />
    </van-popup>

    <van-popup v-model:show="showZodiacPicker" position="bottom">
      <van-picker
        :columns="zodiacColumns"
        @confirm="onZodiacConfirm"
        @cancel="showZodiacPicker = false"
        title="选择星座"
        show-toolbar
      />
    </van-popup>

    <van-popup v-model:show="showIncomePicker" position="bottom">
      <van-picker
        :columns="incomeColumns"
        @confirm="onIncomeConfirm"
        @cancel="showIncomePicker = false"
        title="选择月收入"
        show-toolbar
      />
    </van-popup>

    <van-popup v-model:show="showMaritalStatusPicker" position="bottom">
      <van-picker
        :columns="maritalStatusColumns"
        @confirm="onMaritalStatusConfirm"
        @cancel="showMaritalStatusPicker = false"
        title="选择婚姻状况"
        show-toolbar
      />
    </van-popup>

    <van-popup v-model:show="showHousingPicker" position="bottom">
      <van-picker
        :columns="housingColumns"
        @confirm="onHousingConfirm"
        @cancel="showHousingPicker = false"
        title="选择住房情况"
        show-toolbar
      />
    </van-popup>

    <van-popup v-model:show="showCarPicker" position="bottom">
      <van-picker
        :columns="carColumns"
        @confirm="onCarConfirm"
        @cancel="showCarPicker = false"
        title="是否有车"
        show-toolbar
      />
    </van-popup>

    <van-popup v-model:show="showAcceptDivorcedPicker" position="bottom">
      <van-picker
        :columns="acceptDivorcedColumns"
        @confirm="onAcceptDivorcedConfirm"
        @cancel="showAcceptDivorcedPicker = false"
        title="是否接受离异"
        show-toolbar
      />
    </van-popup>

    <!-- 添加出生年份选择器 -->
    <van-popup v-model:show="showBirthYearPicker" position="bottom">
      <van-picker
        :columns="birthYearColumns"
        @confirm="onBirthYearConfirm"
        @cancel="showBirthYearPicker = false"
        title="选择出生年份"
        show-toolbar
      />
    </van-popup>

    <van-popup v-model:show="showGenderPicker" position="bottom">
      <van-picker
        :columns="genderColumns"
        @confirm="onGenderConfirm"
        @cancel="showGenderPicker = false"
        title="选择性别"
        show-toolbar
      />
    </van-popup>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import { showToast, showDialog } from "vant";
import request from "@/utils/request";

const router = useRouter();
const route = useRoute();
const formRef = ref(null);
const submitting = ref(false);
const loading = ref(false);

// 判断是否是编辑模式
const isEditMode = computed(() => route.query.mode === "edit");
const userId = computed(() => route.query.id);

// 表单数据
const formData = reactive({
  // 基础信息
  name: "",
  gender: "男",
  birth_year: "",
  hometown: "临沂",
  contact: "",
  work_location: "临沂",
  education: "",
  marital_status_desc: "未婚",

  // 个人条件
  height: "",
  weight: "",
  zodiac: "",
  occupation: "",
  income: "",
  family: "",
  housing: "租房",
  car: "否",

  // 兴趣爱好
  hobbies: "",
  personality: "",

  // 择偶标准
  accept_divorced: "否",
  requirements: "",

  // 照片与介绍
  photos: [],
  photo_urls: [],
  introduction: "",
});

// 选择器相关
const showEducationPicker = ref(false);
const showZodiacPicker = ref(false);
const showIncomePicker = ref(false);
const showMaritalStatusPicker = ref(false);
const showHousingPicker = ref(false);
const showCarPicker = ref(false);
const showAcceptDivorcedPicker = ref(false);
const showBirthYearPicker = ref(false);
const showGenderPicker = ref(false);

const educationColumns = [
  { text: "初中及以下", value: "初中及以下" },
  { text: "高中", value: "高中" },
  { text: "大专", value: "大专" },
  { text: "本科", value: "本科" },
  { text: "硕士", value: "硕士" },
  { text: "博士", value: "博士" },
];

const zodiacColumns = [
  { text: "白羊座", value: "白羊座" },
  { text: "金牛座", value: "金牛座" },
  { text: "双子座", value: "双子座" },
  { text: "巨蟹座", value: "巨蟹座" },
  { text: "狮子座", value: "狮子座" },
  { text: "处女座", value: "处女座" },
  { text: "天秤座", value: "天秤座" },
  { text: "天蝎座", value: "天蝎座" },
  { text: "射手座", value: "射手座" },
  { text: "摩羯座", value: "摩羯座" },
  { text: "水瓶座", value: "水瓶座" },
  { text: "双鱼座", value: "双鱼座" },
];

const incomeColumns = [
  { text: "3000以下", value: "3000以下" },
  { text: "3000-5000", value: "3000-5000" },
  { text: "5000-8000", value: "5000-8000" },
  { text: "8000-12000", value: "8000-12000" },
  { text: "12000-20000", value: "12000-20000" },
  { text: "20000以上", value: "20000以上" },
];

const maritalStatusColumns = [
  { text: "未婚", value: "未婚" },
  { text: "离异无子女", value: "离异无子女" },
  { text: "离异有子女", value: "离异有子女" },
  { text: "丧偶", value: "丧偶" },
];

const housingColumns = [
  { text: "租房", value: "租房" },
  { text: "有房", value: "有房" },
  { text: "与家人同住", value: "与家人同住" },
];

const carColumns = [
  { text: "是", value: "是" },
  { text: "否", value: "否" },
];

const acceptDivorcedColumns = [
  { text: "是", value: "是" },
  { text: "否", value: "否" },
];

// 生成1960-2005年的年份选择器数据
const birthYearColumns = Array.from({ length: 46 }, (_, i) => ({
  text: String(2005 - i),
  value: String(2005 - i),
}));

const genderColumns = [
  { text: "男", value: "男" },
  { text: "女", value: "女" },
];

// 选择器确认事件
const onEducationConfirm = ({ selectedOptions }) => {
  formData.education = selectedOptions[0].value;
  showEducationPicker.value = false;
};

const onZodiacConfirm = ({ selectedOptions }) => {
  formData.zodiac = selectedOptions[0].value;
  showZodiacPicker.value = false;
};

const onIncomeConfirm = ({ selectedOptions }) => {
  formData.income = selectedOptions[0].value;
  showIncomePicker.value = false;
};

const onMaritalStatusConfirm = ({ selectedOptions }) => {
  formData.marital_status_desc = selectedOptions[0].value;
  showMaritalStatusPicker.value = false;
};

const onHousingConfirm = ({ selectedOptions }) => {
  formData.housing = selectedOptions[0].value;
  showHousingPicker.value = false;
};

const onCarConfirm = ({ selectedOptions }) => {
  formData.car = selectedOptions[0].value;
  showCarPicker.value = false;
};

const onAcceptDivorcedConfirm = ({ selectedOptions }) => {
  formData.accept_divorced = selectedOptions[0].value;
  showAcceptDivorcedPicker.value = false;
};

const onBirthYearConfirm = ({ selectedOptions }) => {
  formData.birth_year = selectedOptions[0].value;
  showBirthYearPicker.value = false;
};

const onGenderConfirm = ({ selectedOptions }) => {
  formData.gender = selectedOptions[0].value;
  showGenderPicker.value = false;
};

// 表单验证
const validateHeight = (val) => {
  const height = Number(val);
  return !val || (height >= 140 && height <= 220);
};

const validateWeight = (val) => {
  if (!val) return true;
  const weight = Number(val);
  return weight >= 30 && weight <= 150;
};

// 修改照片上传前的处理函数
const beforePhotoRead = (file) => {
  if (Array.isArray(file)) {
    return file.every((item) => {
      const isImage = item.type.indexOf("image") !== -1;
      if (!isImage) {
        showToast("请上传图片格式文件");
        return false;
      }
      if (item.size > 10 * 1024 * 1024) {
        showToast("图片大小不能超过10M");
        return false;
      }
      return true;
    });
  }
  const isImage = file.type.indexOf("image") !== -1;
  if (!isImage) {
    showToast("请上传图片格式文件");
    return false;
  }
  if (file.size > 10 * 1024 * 1024) {
    showToast("图片大小不能超过10M");
    return false;
  }
  return true;
};

// 修改照片处理函数
const handlePhotoChange = async (file) => {
  const uploadFile = async (item) => {
    try {
      item.status = "uploading";
      item.message = "上传中...";
      const form = new FormData();
      form.append("file", item.file);

      const response = await request({
        url: "/users/upload",
        method: "post",
        headers: {
          "Content-Type": "multipart/form-data",
        },
        data: form,
      });

      if (response.data) {
        item.url = response.data.url;
        formData.photo_urls.push(response.data.url);
        item.status = "done";
        item.message = "";
        showToast("照片上传成功");
      }
    } catch (error) {
      console.error("照片上传失败:", error);
      item.status = "failed";
      item.message = "上传失败";
      showToast("照片上传失败，请重试");
      const index = formData.photos.indexOf(item);
      if (index > -1) {
        formData.photos.splice(index, 1);
      }
    }
  };

  if (Array.isArray(file)) {
    for (const item of file) {
      await uploadFile(item);
    }
  } else {
    await uploadFile(file);
  }
};

// 修改照片删除函数
const handlePhotoRemove = (file) => {
  const index = formData.photos.indexOf(file);
  if (index > -1) {
    formData.photos.splice(index, 1);
  }
  return true;
};

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    loading.value = true;
    const response = await request({
      url: `/users/detail/${userId.value}`,
      method: "get",
    });

    if (!response.data) {
      throw new Error("获取用户信息失败");
    }

    // 处理照片URL
    if (response.data.photo_urls) {
      response.data.photo_urls = response.data.photo_urls.map((url) => {
        if (!url) return "";
        if (url.startsWith("http")) return url;
        return `${import.meta.env.VITE_UPLOAD_URL}${url}`;
      });
      response.data.photos = response.data.photo_urls.map((url) => ({
        url,
        status: "done",
        message: "",
      }));
    }

    // 更新表单数据
    Object.assign(formData, response.data);
  } catch (error) {
    console.error("获取用户信息失败:", error);
    showToast("获取用户信息失败");
    router.back();
  } finally {
    loading.value = false;
  }
};

// 如果是编辑模式，获取用户信息
onMounted(async () => {
  if (isEditMode.value && userId.value) {
    await fetchUserInfo();
  }
});

// 返回处理
const handleBack = () => {
  showDialog({
    title: "提示",
    message: "确定要放弃填写吗？已填写的信息将不会保存。",
    showCancelButton: true,
  }).then(() => {
    router.back();
  });
};

// 提交表单
const onSubmit = async () => {
  try {
    submitting.value = true;
    const response = await request({
      url: "/users/signup",
      method: "post",
      data: {
        ...formData,
        height: parseInt(formData.height),
        weight: formData.weight ? parseInt(formData.weight) : undefined,
        id: isEditMode.value ? userId.value : undefined,
      },
    });

    showToast(isEditMode.value ? "修改成功" : "报名成功");
    if (isEditMode.value) {
      router.back();
    } else {
      router.replace({
        path: "/success",
        query: { id: response.data.id },
      });
    }
  } catch (error) {
    console.error("提交失败:", error);
    if (error.response?.data?.message) {
      showToast(error.response.data.message);
    } else if (error.message) {
      showToast(error.message);
    } else {
      showToast("提交失败，请稍后重试");
    }
  } finally {
    submitting.value = false;
  }
};
</script>

<style scoped>
:deep(.van-field__label) {
  width: 6em !important;
}

:deep(.required::before) {
  content: "*";
  color: var(--van-danger-color);
  margin-right: 4px;
}

:deep(.van-cell-group__title) {
  padding: 8px 16px 4px;
  font-size: 14px;
}

:deep(.van-uploader) {
  padding: 8px 0;
}

:deep(.van-uploader__wrapper) {
  gap: 8px;
}

:deep(.van-uploader__preview) {
  margin: 0;
}

:deep(.van-uploader__upload) {
  margin: 0;
}

:deep(.van-field__control) {
  font-size: 14px;
}

:deep(.van-cell) {
  padding-top: 10px;
  padding-bottom: 10px;
}
</style>
